package com.example.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.example.common.Result;
import com.example.entity.Admin;
import com.example.entity.Params;
import com.example.entity.Type;
import com.example.exception.CustomException;
import com.example.service.AdminService;
import com.example.service.TypeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
@RequestMapping("/type")
public class TypeController {

    private static final Logger log = LoggerFactory.getLogger(TypeController.class);

    @Autowired
    private TypeService typeService;

    //查询所有图书分类信息 （不要分页查询的那种）
    @GetMapping
    public Result allType(){
        return Result.success(typeService.list());
    }

    @GetMapping("/search")
    public Result findBySearch(Params params){

        //1.开启分页
        PageHelper.startPage(params.getPageNum(),params.getPageSize());
        //2.查询信息
        List<Type> list = typeService.findBySearch(params);
        System.out.println(list);
        //3.封装对象
        PageInfo<Type> info = PageInfo.of(list);
        return Result.success(info);
    }


    @PostMapping
    public Result save(@RequestBody Type type){
        typeService.add(type);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result del(@PathVariable Integer id){
        typeService.removeById(id);
        return Result.success();
    }


    @PutMapping("/delBatch")
    public Result delBatch(@RequestBody List<Type> list){
        List<Integer> ids = list.stream().map(Type::getId).collect(Collectors.toList());
        return Result.success(typeService.removeBatchByIds(ids));
    }

    // 批量导出
    @GetMapping("/export")
    public Result export(HttpServletResponse response) throws IOException {
        //1. 查询出所有的数据
        List<Type> types = typeService.list();
        if (CollectionUtils.isEmpty(types)){
            throw new CustomException("未找到数据~~");
        }

        //2. 封装对象: List<Map<String,Object>>, 把一个Map对象当作一个实体类
        // map的key就是字段名，value就是字段值
        List<Map<String, Object>> list = new ArrayList<>(types.size());
        for (Type type : types) {
            Map<String, Object> row = new HashMap<>();
            row.put("分类名称",type.getName());        // 类似：row.setName(type.getName())
            row.put("分类描述",type.getDescription()); // 类似：row.setDescription(type.getDescription())
            list.add(row);
        }

        //3. 下载
        ExcelWriter writer = new ExcelWriter(true);
        writer.write(list,true); // 确认把map的key作为excel的头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition","attachment;filename=type.xlsx");
        ServletOutputStream os = response.getOutputStream();
        writer.flush(os,true);
        writer.close();
        IoUtil.close(System.out);

        return Result.success();
    }


    // 批量导入
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        //1. 读取excel文件，为了映射 列名和实体字段名，需要在字段上起别名
        List<Type> types = ExcelUtil.getReader(file.getInputStream()).readAll(Type.class);

        //2. 入库
        if (CollectionUtils.isNotEmpty(types)){
            for (Type type : types) {
                try {
                    typeService.add(type);
                } catch (Exception e) {
                    e.printStackTrace(); //异常也不影响不异常的数据入库
                }
            }
        }

        return Result.success();
    }

}

